//
//  ST_PeculiaritySquareTypeListController.swift
//  btvideo
//
//  Created by mac on 2020/1/15.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MJRefresh

//人气 推荐 最爱 列表-Controller
class ST_PeculiaritySquareTypeListController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.white
        
        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        view.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        view.addSubview(right_nav_btn)
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        right_nav_btn.snp.makeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-14)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        right_nav_btn.isHidden = true
        
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        

         
        view.insertSubview(collectionView, belowSubview: own_navigation_bar)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        self.request_data()
        
    }

    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,"type":model.listType] as [String : Any]
        
        JVrequest(PH.peculiaritySquarelistNodesApi,parameters:param, success: { (json) in
            
            print("最爱 人气 推荐 详情:",json)
            
            let data = json["data"]
            
            self.model.moreDataBackgroundImageUrl = data["img"].stringValue
            
            let dataStr = data["list"].rawString() ?? ""
            
            if let aArray = [ST_PeculiarityModel].deserialize(from: dataStr) as? [ST_PeculiarityModel]{
                
                if self.currentPage == 1{
                    self.data_array = aArray
                }else{
                    self.data_array += aArray
                }
                
                self.collectionView.reloadData()
                
                self.load_more_option_style(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
                    
                    self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
                
            }else{
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                self.data_array.removeAll()
                self.collectionView.reloadData()
            }
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }

    //     MARK: - Properties
    var model = ST_PeculiaritySquareCollectionCellModel(){
        didSet{
            self.title_nav_btn.setTitleForAllStates(model.title)
        }
    }

    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("特质_icon_返回"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
//        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var right_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("个人中心_icon_更多操作B"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        //        control.cornerRadius = 18
         
//        control.setTitleForAllStates("帮助")
//        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        control.addTarget(self, action: #selector(right_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        
        control.addTarget(self, action: #selector(title_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
       

   fileprivate lazy var layout:UICollectionViewFlowLayout = {
      let controlLayout = UICollectionViewFlowLayout()
       controlLayout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 175*(ScreenWidth/375.0))
       controlLayout.minimumLineSpacing = 20
       controlLayout.minimumInteritemSpacing = 0
       controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 15, bottom: BTSafeAreaBottom + 49, right: 15)
        let w = (ScreenWidth - 15*4)/3
        controlLayout.itemSize = CGSize.init(width: w, height: w+50)
       return controlLayout
   }()
   
   fileprivate lazy var collectionView:UICollectionView = {
       let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
       control.delegate = self
       control.dataSource = self
       control.register(cellWithClass: ST_PeculiarityTypeCell.self)
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_PeculiaritySquareTypeSupplementView.self)
       if #available(iOS 11.0, *) {
           control.contentInsetAdjustmentBehavior = .never
       }
       control.backgroundColor = Color.white
       
       control.alwaysBounceVertical = true
       control.showsVerticalScrollIndicator = false
       control.showsHorizontalScrollIndicator = false
       return control
   }()
    
    fileprivate var data_array = [ST_PeculiarityModel]()

}

extension ST_PeculiaritySquareTypeListController{
    
    @objc func title_click(){
        
    }
    @objc func right_click(){
        
    }
    @objc func left_click(){
        
        self.goback_previous_controller()
    }
}

extension ST_PeculiaritySquareTypeListController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    // MARK: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_PeculiarityTypeCell.self, for: indexPath)
        
        cell.child_model = data_array[indexPath.item]
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_PeculiaritySquareTypeSupplementView.self, for: indexPath)
        
        view.model = self.model
        
        return view
    }

    // MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        push_peculiarity(pec: data_array[indexPath.row], navigationController: self.navigationController)
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
//        print("打印当前的Y:",scrollView.contentOffset.y," -- headerReferenceSize:",layout.headerReferenceSize)
        
        
        let y = scrollView.contentOffset.y
        
        let offSet = layout.headerReferenceSize.height - y
        
        if offSet < 0{
            
            own_navigation_bar.alpha = 1
            
        }else if offSet >= own_navigation_bar_show_coefficient{
            own_navigation_bar.alpha = 0
        }else{
            own_navigation_bar.alpha = 1-offSet/own_navigation_bar_show_coefficient
        }
    }
}
